package de.velvettear.bruteforce.kernel.threads;

import java.io.File;
import java.math.BigInteger;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import de.velvettear.bruteforce.kernel.WordList;
import de.velvettear.bruteforce.util.DirectoryHelper;
import de.velvettear.bruteforce.util.FileHelper;
import de.velvettear.bruteforce.util.Log;

public class WorkThread extends Thread {
	
	private static String NAME;
	private static File SOURCE; 
	private static File DIRECTORY;
		
	private static boolean threadRunning = false;
	private static boolean passwordFound = false;
		
	public WorkThread(String threadName, File source) {
		NAME = threadName;
		
		DIRECTORY = DirectoryHelper.createTemporaryThreadDirectory(NAME);
		SOURCE = FileHelper.copyToTemporaryThreadDirectory(NAME, source);		
	}
	
	@Override
	public void run() {
		threadRunning = true;
				
		int index = 1;				
		while (threadRunning && !passwordFound) {				
			String word = WordList.inMemory.get(new BigInteger(String.valueOf(index)));
			WordList.inMemory.remove(new BigInteger(String.valueOf(index)));		
						
			System.out.println(NAME + " - " + word);
			
			if (word == null) {
				index++;	
			} else {
				try {
					if (SOURCE.exists() && DIRECTORY.exists() && DIRECTORY.isDirectory()) {
						ZipFile zip = new ZipFile(SOURCE);
						if (zip.isValidZipFile()) {
							if (zip.isEncrypted()) {
								zip.setPassword(word);
							}
							zip.extractAll(DIRECTORY.getAbsolutePath());
							passwordFound = true;
						}
					}					
				} catch (ZipException ze) {
					
				} catch (Exception e) {
					Log.error(e);
				}
				index++;
			}
		}
		
		if (passwordFound) {
			for (File tmp : DIRECTORY.listFiles()) {
				FileHelper.copy(tmp, new File("D:\\Test\\result"), true);
			}
		}
		
		DirectoryHelper.deleteTemporaryThreadDirectory(NAME);
		threadRunning = false;		
	}
		
	public static void kill() {
		threadRunning = false;
	}
	
	public static boolean isRunning() {
		return threadRunning;
	}
	
}
